package com.trinhrae.shooting.moduleGeneral.service;

import com.trinhrae.shooting.entity.MailRequest;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: TrinhRae
 * @Package: com.trinhrae.shooting.moduleGeneral.service
 * @Project: shooting
 * @Date: 2025/9/12 9:48
 */
@Service
public class EmailService {
    private final JavaMailSender javaMailSender;

    private final Configuration freemarkerConfig;

    @Value("${spring.mail.username}")
    private String sendMailer;

    public EmailService(JavaMailSender javaMailSender, Configuration freemarkerConfig) {
        this.javaMailSender = javaMailSender;
        this.freemarkerConfig = freemarkerConfig;
    }

    /**
     * 发送简单邮件
     *
     * @param mailRequest
     */
    public void sendSimpleMail(MailRequest mailRequest) {
        SimpleMailMessage message = new SimpleMailMessage();
        //邮件发件人
        message.setFrom(sendMailer);
        //邮件收件人 1或多个
        message.setTo(mailRequest.getSendTo().split(","));
        //邮件主题
        message.setSubject(mailRequest.getSubject());
        //邮件内容
        message.setText(mailRequest.getText());
        //邮件发送时间
        message.setSentDate(new Date());
        javaMailSender.send(message);
    }

    public void sendHtmlMail(MailRequest mailRequest) throws MessagingException, IOException, TemplateException {
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
        helper.setFrom(sendMailer);
        helper.setTo(mailRequest.getSendTo());
        helper.setSubject(mailRequest.getSubject());

        // 构成邮件
        Map<String, Object> module = new HashMap<>();
        module.put("username", mailRequest.getSendTo());
        module.put("code", mailRequest.getText());
        module.put("link", "www.baidu.com");
        Template verifyCodeHtml = freemarkerConfig.getTemplate("verify-code.ftl");
        String html = FreeMarkerTemplateUtils.processTemplateIntoString(verifyCodeHtml, module);

        helper.setText(html,true);
        javaMailSender.send(message);
    }
}
